package com.useeinfo.oa.open.mobile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.PinyinUtils;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.Collator;
import java.util.Comparator;
import java.util.List;

/**
 * @program: YiYouFuPlatform
 * @author: Taogq
 * @createDate: 2018-12-26
 * @createTime: 14:50:17
 * 人员信息接口
 */
@RestController
@RequestMapping("/api/mobile/manage/user")
public class UserApiManageAction {

    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private HttpServletRequest request;

    /**
     * 派单人员列表——按权限查
     *
     * @param pageIndex
     * @param pageSize
     * @param userName
     * @return
     */
    @RequestMapping("/listJson")
    public ResultDto listJson(String pageIndex, String pageSize, String userName,String userIds) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (null == enterprise) {
            return ResultUtil.error("用户企业信息有误，请确认");
        }
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        String hql = "select obj from SystemUser obj where obj.operationRole='common' and exists (select ep from obj.enterpriseSet ep where ep.id=" + enterprise.getId() + " ) " +
                "  and exists ( select ure from UserRoleEnterprise ure where ure.systemUser.id = obj.id and ure.enterprise.id = " + enterprise.getId() + "" +
                "  and exists( select auth from ure.systemRole.authoritySet auth where auth.authorityName='ROLE_ENTERPRISE_REPAIR_ORDER_TAKING')) ";
        if(StringUtils.isNotBlank(StringUtils.strip(userIds,"[]"))){
            hql +=  "and obj.id not in ("+ StringUtils.strip(userIds,"[]") + ") ";
        }
        if (!StringConverters.null2String(userName).equals("")) {
            hql += " and obj.userName like '%" + StringConverters.null2String(userName) + "%'";
        }

        List<SystemUser> systemUserList = systemUserBiz.hqlExcute(hql, queryParam);
        JSONArray jsonArray = new JSONArray();
        for (SystemUser systemUser : systemUserList) {
            jsonArray.add(systemUser.toJSONObject());
        }

       /* queryParam.getSqlMap().put("enterpriseIds",enterprise.getId().toString());
        queryParam.getSqlMap().put("operationRoles","common");//只查普通用户
        if(!StringConverters.null2String(userName).equals("")){
            queryParam.getSqlMap().put("userName",userName);
        }*/
        return ResultUtil.success(jsonArray);
    }

    /**
     * 用户修改密码
     *
     * @param old_password
     * @param password
     * @return
     */
    @RequestMapping("/resetPassword")
    public ResultDto resetPassword(String old_password, String password) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (null == systemUser) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (StringUtils.isBlank(old_password) || StringUtils.isBlank(password) || !old_password.equals(systemUser.getUserPassword())) {
            return ResultUtil.error("密码不正确！");
        }
        systemUser.setUserPassword(password);
        systemUserBiz.addOrUpdate(systemUser);
        return ResultUtil.success();
    }


    /**
     *通讯录人员——列表
     * @param pageIndex
     * @param pageSize
     * @param userName
     * @return
     */
    @RequestMapping("/userListJson")
    public ResultDto listJson(String pageIndex, String pageSize, String userName) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (null == enterprise) {
            return ResultUtil.error("用户企业信息有误，请确认");
        }
        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        String hql = "select obj from SystemUser obj where obj.operationRole='common' and obj.deleteStatus=false and exists (select ep from obj.enterpriseSet ep where ep.id=" + enterprise.getId() + " )";

        if (!StringConverters.null2String(userName).equals("")) {
            hql += " and obj.userName like '%" + StringConverters.null2String(userName) + "%'";
        }

        List<SystemUser> systemUserList = systemUserBiz.hqlExcute(hql);
        Comparator<SystemUser> comparator = (user1, user2) -> {
            Collator collator = Collator.getInstance();
            return collator.getCollationKey(PinyinUtils.getAlpha(user1.getUserName()).substring(0,1)).compareTo(
                    collator.getCollationKey(PinyinUtils.getAlpha(user2.getUserName()).substring(0,1)));
        };
        systemUserList.sort(comparator);
        JSONArray result = new JSONArray();
        for(SystemUser systemUser : systemUserList){
            JSONObject jsonObject = systemUser.toJSONObject();
            jsonObject.put("letter",PinyinUtils.getAlpha(systemUser.getUserName()).substring(0,1).toUpperCase());
            jsonObject.put("enterpriseName",enterprise.getEnterpriseName());
            result.add(jsonObject);
        }
        return ResultUtil.success(result);
    }

}
